/*
 * Copyright 2004-2005 asoft
 * 本软件及其所有拷贝的名称，与光盘上或本软件中注明的公司同在。
 * 本软件及文档享有版权，并受国家版权法及国际协约条款的保护。
 * 您不可以从本软件中去掉其版权声明；并保证为本软件的拷贝（本部或部分）* 复制版权声明。
 * 您同意制止以任何形式非法拷贝本软件及文档。
 * 版权信息参见：
 *      http://www.asoft.cn/licenses
 */

package com.asoft.common.util.mvc.valid;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;

import com.asoft.common.base.manager.Manager;
import com.asoft.common.base.model.BaseObject;
import com.asoft.common.sysframe.define.SysFrameParams;
import com.asoft.common.sysframe.manager.OrgManager;
import com.asoft.common.sysframe.manager.PostManager;
import com.asoft.common.sysframe.manager.RoleManager;
import com.asoft.common.sysframe.manager.UserManager;
import com.asoft.common.sysframe.model.User;

/**
 * 用户自定义校验器
 *
 * author: amon_lei created in ：2005-4-6 22:03
 */

public abstract class UserValidator
{
        static Logger logger = Logger.getLogger(UserValidator.class);
        
        private ApplicationContext applicationContext; // spring's

        public void setApplicationContext(ApplicationContext applicationContext)
        {
                this.applicationContext = applicationContext;
        }

        public Object getBean(String beanId)
        {
                return this.applicationContext.getBean(beanId);
        }
        
        /**
         * 校验string
         * 
         * @param request 
         * @param vr
         * @param key request参数的key
         * @param minLength 最小长度
         * @param maxLength 最大长度
         * @param nullErrMess 空值的提示信息
         * @return key对应的value
         */
        public String validString(HttpServletRequest request,
                                  ValidatedResult vr,
                                  String key,
                                  int minLength,
                                  int maxLength,
                                  String nullErrMess)
        {
                String value = request.getParameter(key);
                if((value == null || value.length() == 0) && minLength > 0 )
                {
                        vr.setErrMess(key,nullErrMess);
                }
                else
                {
                        if(value.length() < minLength)
                        {
                                vr.setErrMess(key,"长度不能少于" + minLength);
                                return value;
                        }
                                
                        if(value.length() > maxLength)
                        {
                                vr.setErrMess(key,"长度不能超过" + maxLength);
                                return value;
                        }
                }
                logger.debug(key + " : " + value);
                return value;
        }
        
        /**
         * 校验string
         * 
         * @param request 
         * @param vr
         * @param key request参数的key
         * @param minLength 最小长度
         * @param maxLength 最大长度
         * @param nullErrMess 空值的提示信息
         */
        public String validString(HttpServletRequest request,
                                  ValidatedResult vr,
                                  String key,
                                  int minLength,
                                  int maxLength)
        {
                return this.validString(request,
                                        vr,
                                        key,
                                        minLength,
                                        maxLength,
                                        "必须填写");
        }
        
        /**
         * 校验BaseObject
         * 
         * @param request
         * @param vr
         * @param manager 
         * @param key 
         * @param exceptionMess manager.get(id)异常时候的错误提示
         * @return
         */
        public BaseObject validBaseObjectById(HttpServletRequest request,
                                              ValidatedResult vr,
                                              Manager manager,
                                              String key,
                                              String exceptionMess)
        {
                String id = request.getParameter(key);
                logger.debug(key + " : " + id);
                try
                {
                        return (BaseObject)manager.get(id);
                }
                catch(Exception x)
                {
                        vr.setErrMess(key,exceptionMess);
                        return null;
                }
        }
        
        /**
         * 校验BaseObject
         * 
         * @param request
         * @param vr
         * @param manager 
         * @param key 
         * @param exceptionMess manager.get(id)异常时候的错误提示
         * @return
         */
        public BaseObject validBaseObjectById(HttpServletRequest request,
                                              ValidatedResult vr,
                                              String managerBeanId,
                                              String key,
                                              String exceptionMess)
        {
                Manager manager = (Manager)this.getBean(managerBeanId);
                return this.validBaseObjectById(request,vr,manager,key,exceptionMess);
        }

        /**
         * 校验BaseObject
         * 
         * @param request
         * @param vr
         * @param manager 
         * @param key 
         * @param id
         * @param exceptionMess manager.get(id)异常时候的错误提示
         * @return
         */
        public BaseObject validBaseObjectById(HttpServletRequest request,
                                              ValidatedResult vr,
                                              String managerBeanId,
                                              String key,
                                              Serializable id,
                                              String exceptionMess)
        {

                Manager manager = (Manager)this.getBean(managerBeanId);
                return this.validBaseObjectById(request,vr,manager,key,id,exceptionMess);
        }
        
        // 直接返回null
        public BaseObject validBaseObjectById(HttpServletRequest request,
                                              ValidatedResult vr,
                                              String managerBeanId,
                                              String key)
        {
                String id = request.getParameter(key);
                logger.debug(key + " : " + id);
                Manager manager = (Manager)this.getBean(managerBeanId);
                try
                {
                        return (BaseObject)manager.get(id);
                }
                catch(Exception x)
                {
                        logger.error("取model by id 异常：" + x.toString());
                        vr.setErrMess(key,x.toString());
                        return null;
                }
        }
        
        public BaseObject validBaseObjectById(HttpServletRequest request,
                                              ValidatedResult vr,
                                              Manager manager,
                                              String key)
        {
                String id = request.getParameter(key);
                logger.debug(key + " : " + id);
                Object bo = manager.get(id);
                if(bo == null)
                {
                        vr.setErrMess(key,"无此记录");
                        return null;
                }
                else
                {
                        return (BaseObject)bo;
                }
        }
        
        /**
         * 校验BaseObject
         * 
         * @param request
         * @param vr
         * @param manager 
         * @param key 
         * @param id
         * @param exceptionMess manager.get(id)异常时候的错误提示
         * @return
         */
        public BaseObject validBaseObjectById(HttpServletRequest request,
                                              ValidatedResult vr,
                                              Manager manager,
                                              String key,
                                              Serializable id,
                                              String exceptionMess)
        {
                logger.debug(key + " : " + id);
                try
                {
                        return (BaseObject)manager.get(id);
                }
                catch(Exception x)
                {
                        logger.error(x.toString());
                        vr.setErrMess(key,exceptionMess);
                        return null;
                }
        }
        
        /**
         * 校验timestamp格式是否正确
         * 
         * @param request
         * @param vr
         * @param key 
         * @param par java.text.SimpleDateFormat支持的格式(yyyy-MM-dd hh:mm:ss)
         * @param notNull 不为空
         * @return
         */
        public Timestamp validTimestamp(HttpServletRequest request,
                                        ValidatedResult vr,
                                        String key,
                                        String par,
                                        boolean notNull)
        {
                String time = request.getParameter(key);
                logger.debug(key + " : " + time);
                SimpleDateFormat sdf = new SimpleDateFormat(par);
                if(!notNull )
                {
                        if(time == null || time.equals(""))
                        {
                                return null;
                        }
                }
                else
                {
                        if(time == null || time.equals(""))
                        {
                                vr.setErrMess(key,"必须填写");
                                return null ;
                        }
                }
                try
                {
                        return new Timestamp(sdf.parse(time).getTime());
                }
                catch(ParseException pe)
                {
                        vr.setErrMess(key,"格式必须为" + par);
                        return null;
                }
        }

        
        /**
         * 校验int型
         * 
         * @param request
         * @param vr
         * @param key 关键字
         * @param notNull 不允许为空
         * @return
         */
        public int validInt(HttpServletRequest request,
                            ValidatedResult vr,
                            String key,
                            boolean notNull)
        {
                String value = request.getParameter(key);
                logger.debug(key + " : " + value);
                if(!notNull)
                {
                        if(value == null || value.equals(""))
                        {
                                return 0;
                        }
                }
                else
                {
                        if(value == null || value.equals(""))
                        {
                                vr.setErrMess(key,"必须填写");
                        }
                }
                try
                {
                        return Integer.parseInt(value);
                }
                catch(NumberFormatException nfe)
                {
                        vr.setErrMess(key,"必须为数字");
                        return 0;
                }
        }
        
        /**
         * 校验long型
         * 
         * @param request
         * @param vr
         * @param key 关键字
         * @param notNull 不允许为空
         * @return
         */
        public long validLong(HttpServletRequest request,
                            ValidatedResult vr,
                            String key,
                            boolean notNull)
        {
                String value = request.getParameter(key);
                logger.debug(key + " : " + value);
                if(!notNull)
                {
                        if(value == null || value.equals(""))
                        {
                                return 0;
                        }
                }
                else
                {
                        if(value == null || value.equals(""))
                        {
                                vr.setErrMess(key,"必须填写");
                        }
                }
                try
                {
                        return Long.parseLong(value);
                }
                catch(NumberFormatException nfe)
                {
                        vr.setErrMess(key,"必须为数字");
                        return 0;
                }
        }
        
        /**
         * 校验double型
         * 
         * @param request
         * @param vr
         * @param key 关键字
         * @param notNull 不允许为空
         * @return
         */
        public double validDouble(HttpServletRequest request,
                                ValidatedResult vr,
                                String key,
                                boolean notNull)
        {
                String value = request.getParameter(key);
                logger.debug(key + " : " + value);
                if(!notNull)
                {
                        if(value == null || value.equals(""))
                        {
                                return 0;
                        }
                }
                else
                {
                        if(value == null || value.equals(""))
                        {
                                vr.setErrMess(key,"必须填写");
                        }
                }
                try
                {
                        return Double.valueOf(value);
                        
                }
                catch(NumberFormatException nfe)
                {
                        vr.setErrMess(key,"必须为数字");
                        return 0;
                }
        }
        
        // 取得当前用户
        public User getCurrUser(HttpServletRequest request)
        {
                UserManager userManager = (UserManager)this.getBean("userManager");
                return (User)userManager.get((String)request.getSession().getAttribute(SysFrameParams.CURRENT_USER_ID));
        }
        
        public UserManager getUserManager()
        {
                return (UserManager)this.getBean("userManager");
        }
        
        public OrgManager getOrgManager()
        {
                return (OrgManager)this.getBean("orgManager");
        }
        
        public RoleManager getRoleManager()
        {
                return (RoleManager)this.getBean("roleManager");
        }
        
        public PostManager getPostManager()
        {
                return (PostManager)this.getBean("postManager");
        }

        /**
         * 校验
         * @ HttpServletRequest request
         * @ ValidatedResult vr 校验结果器
         *
         * return 校验结果
         *
         * InitValidatorException 校验器初始化异常
         */
        public abstract void validing(HttpServletRequest request,ValidatedResult vr,String[] params);
}
